const users = require('../mongodb/users')
const mongodb = require('../mongodb/index')
const { renameSync } = require("fs");
const uuid = require('uuid')
const path = require('path')
const node_xlsx = require('node-xlsx')

module.exports = function (){
    return (req,res,next)=>{
        const oldName = path.join(__dirname ,'..',req.files[0].path)
        const newName = oldName + '-' + req.files[0].originalname
        renameSync(oldName,newName)

        const arr = []
        const data = node_xlsx.parse(newName)

        data[0].data.forEach(val=>{
            arr.push({
                userid:'user-' + uuid.v1(),
                username:val[0],
                password:val[1],
                regtime:Date.now(),
                isLogin:false,
                token:''
            })
        })
        mongodb.add(users,arr,err=>{
            res.send(JSON.stringify({
                code:1,
                msg:'导入成功'
            }))
        })
    }
}